﻿using FC.NPOI.Utils;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI_MVC.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace NPOI_MVC.Controllers
{
    public class AjaxResult
    {
        /// <summary>
        /// 返回消息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 返回值
        /// </summary>
        public object Obj { get; set; }
        /// <summary>
        /// 返回状态
        /// </summary>
        public string State { get; set; }
    }

    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult UploadFile(HttpPostedFileBase file)
        {
            AjaxResult result = new AjaxResult()
            {
                Message = "上传成功",
                State = "Ok",
            };
            try
            {
                IList<User> users = file.ToModelList<User>();

                if (Session["Users"] != null) Session.Remove("Users");
                Session.Add("Users", users);

                result.Obj = users;
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                result.State = "Error";
            }

            //result.Obj = file.CreateWorkbook().ToList();

            return Json(result);
        }

        public void Download()
        {
            IWorkbook workbook = new HSSFWorkbook();
            
            if (Session["Users"] != null)
            {
                ISheet sheet = workbook.CreateSheet(Session["Users"] as List<User>);

                //强制Excel重新计算表中所有的公式
                sheet.ForceFormulaRecalculation = true;

                //设置响应的类型为Excel
                Response.ContentType = "application/vnd.ms-excel";
                //设置下载的Excel文件名
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "test.xls"));
                //Clear方法删除所有缓存中的HTML输出。但此方法只删除Response显示输入信息，不删除Response头信息。以免影响导出数据的完整性。
                Response.Clear();

                using (MemoryStream ms = new MemoryStream())
                {
                    //将工作簿的内容放到内存流中
                    workbook.Write(ms);
                    //将内存流转换成字节数组发送到客户端
                    Response.BinaryWrite(ms.GetBuffer());
                    Response.End();
                }
            }
        }
    }
}